package com.ruike.alisurface.ui.settings;

import android.content.Intent;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.AppInfoBean;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.https.AppUpdateHttp;
import com.ruike.alisurface.utils.APPUtils;
import com.ruike.alisurface.utils.DialogTipUtils;
import com.ruike.alisurface.utils.GsonUtils;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_http.ApiTools;
import com.voodoo.lib_http.DownloadListener;
import com.voodoo.lib_logcat.L;

import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020/08/18 018 10:11 上午
 * Description: 守护程序操作
 */
public class AppDaemon_Aty extends BaseAty implements ApiListener {

    @BindView(R.id.appDemonSetting_showStatus_llayout)
    LinearLayout showStatusLlayout;
    @BindView(R.id.appDemonSetting_showStatus_tv)
    TextView showStatusTv;
    @BindView(R.id.appDemonSetting_progress_pb)
    ProgressBar progressPb;

    private String downloadPath = Environment.getExternalStorageDirectory().getPath();
    private String downloadFileName = "tempAppDemonApp.apk";

    private boolean isUninstallClick = false;
    private String daemonAppPackage = "com.voodoo.appdaemon";

    @Override
    protected int getLayoutResId() {
        return R.layout.app_setting_demon;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);

    }

    @Override
    protected void initData() {
    }


    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent("com.MainApp.Action.Start"); // 发送主程序启动的广播
        sendBroadcast(intent);
    }

    @OnClick({R.id.appDemonSetting_goback_imgv, R.id.appDemonSetting_openDemon_btn, R.id.appDemonSetting_downloadMainApp_btn, R.id.appDemonSetting_downloadApp_btn})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.appDemonSetting_goback_imgv:
                finish();
                break;
            case R.id.appDemonSetting_openDemon_btn: // 打开守护程序
                // //////////////////////////////////// 此处修改 ////////////////////////////////////
                showProgressDialog("正在获取最新守护程序，请稍后...");
                AppUpdateHttp.getAppVersion(Constant.SHAPP_TYPE, this);

                ////////////////////////////////////////////////////////////////////////////////////
                break;
            case R.id.appDemonSetting_downloadMainApp_btn: // 下载安装主程序 pm uninstall com.ruike.alisurface
                uninstallMainApp();
                break;
            case R.id.appDemonSetting_downloadApp_btn: //
                // 停止服务退出APP
                // 点击的时候发送一条广播出去
                Intent intent = new Intent("com.MainApp.Action.Exit"); // 发送APP退出的广播
                sendBroadcast(intent);
//                stopService(new Intent(this, AppRunMonitoringService.class));
                Intent intent1 = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
                startActivity(intent1);
                break;
        }
    }

    /**
     * 卸载主程序，让守护程序去下载最新版的主程序安装并且打开
     */
    private void uninstallMainApp() {
        if (!isUninstallClick) {
            boolean appInstalled = APPUtils.isAppInstalled(this, daemonAppPackage);
            if (appInstalled) {
                if (APPUtils.isAppRunning(this, daemonAppPackage)) {
                    isUninstallClick = true;
                    showProgressDialog("正在卸载主程序，请稍等...");
                    // ////////////////////////////// 此处修改 //////////////////////////////
                    // 直接卸载本APP
                    APPUtils.uninstallApk(BuildConfig.APPLICATION_ID);
                    ////////////////////////////////////////////////////////////////////////
                } else {
                    showErrorToast("守护程序未运行，请先打开守护程序...");
                }
            } else {
                L.i("tag_请先安装守护程序");
                showErrorToast("请先安装守护程序...");
            }
        }
    }

    boolean downloading;
    // ////////////////////////////////////////// 此处修改 //////////////////////////////////////////

    /**
     * 展示下载守护程序的弹窗
     *
     * @param titleStr    展示标题
     * @param msg         展示消息
     * @param positiveStr 确认按钮文字
     * @param negativeStr 取消按钮文字
     * @param downloadUrl 下载地址
     */
    private void showDownloadDaemonApp(String titleStr, String msg, String positiveStr, String negativeStr, String downloadUrl) {
        DialogTipUtils.showTipDialog(this, msg, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 下载守护程序
                if (DialogTipUtils.xToast != null) {
                    DialogTipUtils.xToast.cancel();
                }
                if (downloading) {
                    showRightToast("有任务正在下载中，请稍等...");
                } else {
                    ApiTools.getInstance().getInstance().download(downloadUrl, downloadPath, downloadFileName, new DownloadListener() {
                        @Override
                        public void onDownloadStart(String url, int id) {

                        }

                        @Override
                        public void onDownloading(String url, long progress, long total, int id) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    downloading = true;
                                    if (showStatusLlayout.getVisibility() == View.GONE) {
                                        showStatusTv.setText("正在下载中...");
                                        showStatusLlayout.setVisibility(View.VISIBLE);
                                    }
                                    progressPb.setProgress((int) progress);
                                }
                            });
                        }

                        @Override
                        public void onDownloadComplete(String url, int id) {
                            downloading = false;
                        }

                        @Override
                        public void onDownloadSuccess(String url, File downloadFile, int id) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showStatusTv.setText("下载成功，正在安装..");
                                    boolean isInstalled = APPUtils.clientInstall(downloadFile.getPath());
                                    if (isInstalled) {
                                        APPUtils.openPackage(AppDaemon_Aty.this, daemonAppPackage);
                                    } else {
                                        showStatusTv.setText("安装失败，请重新安装...");
                                    }
                                    showStatusTv.setVisibility(View.GONE);
                                    progressPb.setVisibility(View.GONE);
                                }
                            });
                        }

                        @Override
                        public void onDownloadFail(String url, String errorMsg, int id) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showStatusTv.setText("下载失败，请重试...");
                                    showErrorToast("下载失败，请重试...");
                                    L.e("下载守护程序失败", "url:" + url, errorMsg);
                                }
                            });
                        }
                    });
                }
            }
        });
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////


    @Override
    protected void onRestart() {
        super.onRestart();
        showStatusTv.setVisibility(View.VISIBLE);
        showStatusTv.setText("启动成功");
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {
        removeProgressDialog();
    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (requestUrl.endsWith("Get_AppVersion")) {

            AppInfoBean appInfoBean = GsonUtils.fromJson(requestJson.toString(), AppInfoBean.class);
            if (appInfoBean.getData().getDownloadUrl().isEmpty()) {
                return;
            }

            if (appInfoBean.getData().getAppProject_id().equals(Constant.SHAPP_TYPE)) {
                // //////////////////////////////////// 此处修改 ////////////////////////////////////
                boolean appInstalled = APPUtils.isAppInstalled(this, daemonAppPackage);
                if (appInstalled) {

                    // 当前安装的守护程序版本号
                    String appdaemonApkPath = APPUtils.getApkPath(this, daemonAppPackage);
                    int apkVersionCode = APPUtils.getApkVersionCode(this, appdaemonApkPath);

                    // 后台回传的守护程序版本号（后台记录的是版本名称，守护程序版本号和版本名称是统一的，例如：版本号：20201027 版本名称：2020.10.27）
                    String versionStr = appInfoBean.getData().getVersion().replace(".", "");
                    int version = Integer.parseInt(versionStr);

                    // 判断本地Apk的VersionCode是否小于后台回传的VersionCode
                    if (apkVersionCode < version) {
                        showDownloadDaemonApp("检测提示",
                                "当前守护程序版本较低，建议您尽快下载新程序",
                                "下载并安装",
                                "稍后下载",
                                appInfoBean.getData().getDownloadUrl());
                    } else { // 后台版本与本地版本一致或本地版本高于后台版本
                        if (APPUtils.isAppRunning(this, daemonAppPackage)) {
                            APPUtils.stopAppByKill(this, daemonAppPackage);
                        }
                        APPUtils.openPackage(this, daemonAppPackage);
                    }
                } else {
                    showDownloadDaemonApp("检测提示",
                            "守护程序未安装，是否下载安装守护程序，建议您尽快下载",
                            "下载并打开",
                            "稍后下载",
                            appInfoBean.getData().getDownloadUrl());
                }
                ////////////////////////////////////////////////////////////////////////////////////
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        if (requestUrl.endsWith("Get_AppVersion")) {
            showErrorToast(errorMsg);
        }
    }
}
